package com.daxia.ogmall.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.daxia.ogmall.basemodel.CoreUser;
import com.daxia.ogmall.dto.AddressDTO;
import com.daxia.ogmall.dto.UserDTO;
import com.daxia.ogmall.util.SpringSecurityUtils;
import com.daxia.ogmall.util.ValidationUtils;

@Controller
@RequestMapping("address")
public class AddressController extends BaseController {
	@ResponseBody
    @RequestMapping(value = "/addAddress")
	public String addAddress(AddressDTO address,Map<String, Object> map) {
		ValidationUtils.assertTrue(StringUtils.isNotBlank(address.getName()), "地址接收人不能为空!");
		ValidationUtils.assertTrue(StringUtils.isNotBlank(address.getAddress()), "接收地址不能为空!");
		ValidationUtils.assertTrue(address.getProvince() != null, "所在省份不能为空!");
		ValidationUtils.assertTrue(address.getCity() != null, "所在省份不能为空!");
		ValidationUtils.assertTrue(address.getDistrict() != null, "所在地区不能为空!");
		ValidationUtils.assertTrue(StringUtils.isNotBlank(address.getMobile()),"手机号码不能为空!");
		ValidationUtils.validateMobile(address.getMobile(), "手机号码格式不正确!");
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
    	ValidationUtils.assertTrue(currentUser != null, "您还没有登陆，请登录后使用地址获取功能!");
    	UserDTO user = new UserDTO();
    	user.setId(currentUser.getId());
    	address.setUser(user);
    	Long addressId = addressService.create(address);
    	if(address.getIsDefault()) {   //如果是设定为默认，那么还要设定默认状态
    		addressService.updateAddressDefault(addressId, currentUser.getId());
    	}
		return okJson();
	}
	
	@ResponseBody
    @RequestMapping(value = "/getAddresses")
	public String getAddresses(Map<String, Object> map) {    //获取用户的地址存放信息
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
    	ValidationUtils.assertTrue(currentUser != null, "您还没有登陆，请登录后使用地址获取功能!");
    	AddressDTO queryAddress =new AddressDTO();
    	UserDTO user = new UserDTO();
    	user.setId(currentUser.getId());
    	queryAddress.setUser(user);
    	List<AddressDTO> addresses = addressService.find(queryAddress, null);
    	JSONObject jObj = new JSONObject();
    	jObj.put("success", true);
    	jObj.put("addresses",addresses);
		return jObj.toJSONString();
	}
}